package com.victorywang.RetrofitWebService;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.victorywang.RetrofitWebService.dsrequest.DsRequestBody;
import com.victorywang.RetrofitWebService.dsrequest.DsRequestEnvelopte;
import com.victorywang.RetrofitWebService.dsrequest.DsRequestModel;
import com.victorywang.RetrofitWebService.dsrequest.DsRequestPara;
import com.victorywang.RetrofitWebService.dsresponse.DsResponseBody;
import com.victorywang.RetrofitWebService.dsresponse.DsResponseEnvelope;
import com.victorywang.RetrofitWebService.dsresponse.DsResponseModel;
import com.victorywang.RetrofitWebService.request.RequestBody;
import com.victorywang.RetrofitWebService.request.RequestEnvelope;
import com.victorywang.RetrofitWebService.request.RequestModel;
import com.victorywang.RetrofitWebService.response.AssetResponseBody;
import com.victorywang.RetrofitWebService.response.AssetResponseEnvelope;
import com.victorywang.RetrofitWebService.response.AssetResponseModel;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private static final OkHttpClient client = new OkHttpClient.Builder().
            connectTimeout(60, TimeUnit.SECONDS).
            readTimeout(60, TimeUnit.SECONDS).
            writeTimeout(60, TimeUnit.SECONDS).
            build();

    EditText etUrl;
    TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        etUrl = (EditText) findViewById(R.id.et_url);
        tvResult = (TextView) findViewById(R.id.tv_result);
        findViewById(R.id.btn_request).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvResult.setText("");
                request();
            }
        });

        findViewById(R.id.btn_requestdataservice).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvResult.setText("");
                requestDataService();
            }
        });
    }

    /**
     * 去服务端请求数据
     */
    private void request() {
        String url = etUrl.getText().toString().trim();
        try {

            // 初始化Retrofit
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .client(client)
                    .addConverterFactory(SimpleXmlConverterFactory.create()) // 返回数据为xml,因此要加入xml解析
                    .build();

            ApiStore apiStore = retrofit.create(ApiStore.class);

            // 初始化请求体
            RequestModel requestModel = new RequestModel(1000);
            RequestBody requestBody = new RequestBody(requestModel);
            RequestEnvelope requestEnvelope = new RequestEnvelope(requestBody);

            // 开始请求
            Call<AssetResponseEnvelope> call = apiStore.getAssetInfo(requestEnvelope);
            call.enqueue(new Callback<AssetResponseEnvelope>() {
                @Override
                public void onResponse(Call<AssetResponseEnvelope> call, Response<AssetResponseEnvelope> response) {
                    // 处理响应体
                    AssetResponseEnvelope responseEnvelope = response.body();
                    if (responseEnvelope == null) {
                        Log.d(TAG, "onResponse: responseEnvelope == null");
                        return;
                    }
                    AssetResponseBody responseBody = responseEnvelope.responseBody;
                    if (responseBody == null) {
                        Log.d(TAG, "onResponse: responseBody == null");
                        return;
                    }
                    AssetResponseModel responseModel = responseBody.responseModel;
                    if (responseModel == null) {
                        Log.d(TAG, "onResponse: responseModel == null");
                        return;
                    }
                    String result = responseModel.result;
                    Log.d(TAG, "onResponse: result : " + result);
                    showResult(result);
                }

                @Override
                public void onFailure(Call<AssetResponseEnvelope> call, Throwable t) {
                    showResult("请求失败");
                }
            });
        } catch (IllegalArgumentException ex) {
            Toast.makeText(this, "IllegalArgumentException", Toast.LENGTH_SHORT);
        }
    }

    /**
     * 向服务器端请求数据
     */
    private void requestDataService() {
        String url = etUrl.getText().toString().trim();

        // 初始化Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(client)
                .addConverterFactory(SimpleXmlConverterFactory.create()) // 返回数据为xml,因此要加入xml解析
                .build();

        DsApiStore apiStore = retrofit.create(DsApiStore.class);

        //!< 请求信息主体
        DsRequestPara dsRequestPara = new DsRequestPara("InforCenter.AndroidService.AndroidService.saveExecutePersonData");
        DsRequestModel dsRequestModel = new DsRequestModel(dsRequestPara, "{\"para\":{\"Lang\":\"zhs\",\"Connect\":\"ORACLE\",\"UserCode\":\"\",\"TASKEID\":\"TASKDETAIL_44626aa433b842fba9a6df3e2cf7b071\",\"SAVEDATA\":\"USERINFO_39da6b6b14c643c39e74cefaaafde301\"}}");
        DsRequestBody dsRequestBody = new DsRequestBody(dsRequestModel);
        DsRequestEnvelopte dsRequestEnvelopte = new DsRequestEnvelopte(dsRequestBody);

        Call<DsResponseEnvelope> call = apiStore.getAssetInfo(dsRequestEnvelopte);
        call.enqueue(new Callback<DsResponseEnvelope>() {
            @Override
            public void onResponse(Call<DsResponseEnvelope> call, Response<DsResponseEnvelope> response) {
                // 处理响应体
                DsResponseEnvelope responseEnvelope = response.body();
                if (responseEnvelope == null) {
                    Log.d(TAG, "onResponse: responseEnvelope == null");
                    return;
                }
                DsResponseBody responseBody = responseEnvelope.dsRequestBody;
                if (responseBody == null) {
                    Log.d(TAG, "onResponse: responseBody == null");
                    return;
                }
                DsResponseModel responseModel = responseBody.dsResponseModel;
                if (responseModel == null) {
                    Log.d(TAG, "onResponse: responseModel == null");
                    return;
                }
                String result = responseModel.sResult;
                Log.d(TAG, "onResponse: result : " + result);
                showResult(result);
            }

            @Override
            public void onFailure(Call<DsResponseEnvelope> call, Throwable t) {
                showResult("请求失败");
            }
        });
    }

    /**
     * 将解析完的数据显示到界面上
     *
     * @param result 解析的数据
     */
    private void showResult(final String result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvResult.setText(result);
            }
        });
    }
}
